﻿using HandyControl.Controls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;

namespace RFID测试软件.View
{
    /// <summary>
    /// TestView.xaml 的交互逻辑
    /// </summary>
    public partial class TestView : UserControl
    {
        ViewModel.TestViewModel viewModel = new ViewModel.TestViewModel();
        DispatcherTimer timer1 = new DispatcherTimer();
        //BLL.TestViewBLL testViewBLL = null;
        BtLabelDAL.HttpDAL httpDAL = new BtLabelDAL.HttpDAL();
        BtLabelBLL.RfidBLL rfidBLL = new BtLabelBLL.RfidBLL();
        BtLabelDAL.RfidDAL rfidDAL = new BtLabelDAL.RfidDAL();
        public TestView()
        {
            try
            {
                //设置为中文
                HandyControl.Tools.ConfigHelper.Instance.SetLang("zh-cn");
                InitializeComponent();
                this.DataContext = viewModel;
                timer1.Tick += new EventHandler(timer1_Tick);
                timer1.Interval = new TimeSpan(TimeSpan.TicksPerMillisecond * 500);
            }
            catch (System.Exception ex)
            {
                Growl.Error(ex.Message);
                BtLabelTool.LogHelper.WriteLog(ex.ToString());
            }
        }


        private void RadioButton_Checked(object sender, RoutedEventArgs e)
        {
            try
            {
                foreach (var item in viewModel.MacItems)
                {
                    if (RadioButtonAll.IsChecked == true && item.ItemHeight == 0)
                    {
                        item.ItemHeight = 40;
                    }
                    if (RadioButtonIng.IsChecked == true)
                    {
                        if (item.BackColor == Brushes.Gold || item.BackColor == Brushes.Tomato)
                        {
                            item.ItemHeight = 40;
                        }
                        else
                        {
                            item.ItemHeight = 0;
                        }
                    }
                    if (RadioButtonPass.IsChecked == true)
                    {
                        item.ItemHeight = item.BackColor == Brushes.YellowGreen ? 40 : 0;
                    }
                }
            }
            catch (System.Exception ex)
            {
                Growl.Error(ex.Message);
                BtLabelTool.LogHelper.WriteLog(ex.ToString());
            }
        }

        private void TextBox_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Key == Key.Enter)
                {
                    if (TextBoxMac.Text.Length != 12)
                    {
                        Growl.Warning("条码长度错误");
                        return;
                    }
                    string mac = TextBoxMac.Text.Trim().ToUpper();
                    mac = mac.Substring(0, 2) + " " + mac.Substring(2, 2) + " " +
                        mac.Substring(4, 2) + " " + mac.Substring(6, 2) + " " +
                        mac.Substring(8, 2) + " " + mac.Substring(10, 2);
                    if (rfidDAL.CheckAddr(mac) == false)
                    {
                        MessageBoxResult result = HandyControl.Controls.MessageBox.Ask("发现重复MAC,确定继续测试？", "警告");
                        if (result == MessageBoxResult.Cancel)
                        {
                            return;
                        }
                    }
                    ViewModel.TestViewModel.Item item = null;
                    var items = viewModel.MacItems.Where(it => it.Mac == mac).ToList();
                    if (items.Count() != 0)
                    {
                        items[0].Read = "wait";
                        items[0].Write = "wait";
                        items[0].Light = "wait";
                        items[0].BackColor = Brushes.Gold;
                        item = items[0];
                    }
                    else
                    {
                        item = new ViewModel.TestViewModel.Item()
                        {
                            id = viewModel.MacItems.Count,
                            Mac = mac,
                            Read = "wait",
                            Write = "wait",
                            Light = "wait",
                            BackColor = Brushes.Gold,
                        };
                        viewModel.MacItems.Add(item);
                    }
                    if (RadioButtonPass.IsChecked == true)
                    {
                        item.ItemHeight = 0;
                    }
                    else
                    {
                        item.ItemHeight = 40;
                    }
                    List.ScrollIntoView(List.Items[item.id]);
                    InitCount();

                    TextBoxMac.IsEnabled = false;
                    TextBoxMac.Clear();

                    Task.Factory.StartNew(() =>
                    {
                        try
                        {
                            List<string> list = new List<string>();
                            list = rfidBLL.GetLabels(30 * 1000);
                            if (list.Count == 0)
                            {
                                Dispatcher.Invoke(() =>
                                {
                                    item.BackColor = Brushes.Tomato;
                                    item.Read = "fail";
                                });
                                goto label1;
                            }
                            Dispatcher.Invoke(() =>
                            {
                                item.Read = "pass";
                            });
                            if (rfidBLL.WriteRfid(mac) == false)
                            {
                                Dispatcher.Invoke(() =>
                                {
                                    item.BackColor = Brushes.Tomato;
                                    item.Write = "fail";
                                });
                                goto label1;
                            }
                            Dispatcher.Invoke(() =>
                            {
                                item.Write = "pass";
                                item.Light = "pass";
                            });
                            var model = new BtLabelModel.RfidDbModel.Rfid_Table()
                            {
                                mac = mac,
                                time = DateTime.Now
                            };
                            if (rfidDAL.Update(model) == false)
                            {
                                Dispatcher.Invoke(() =>
                                {
                                    item.BackColor = Brushes.Tomato;
                                });
                                Growl.Warning("数据上传失败");
                                goto label1;
                            }
                            Dispatcher.Invoke(() =>
                            {
                                item.BackColor = Brushes.YellowGreen;
                                if (RadioButtonIng.IsChecked==true)
                                {
                                    item.ItemHeight = 0;
                                }
                                else
                                {
                                    item.ItemHeight = 40;
                                }
                            });
                        label1:
                            Dispatcher.Invoke(() =>
                            {
                                InitCount();
                                TextBoxMac.IsEnabled = true;
                                TextBoxMac.Focus();
                                TextBoxMac.SelectAll();
                            });
                        }
                        catch (System.Exception ex)
                        {
                            InitCount();
                            Growl.Error(ex.Message);
                            BtLabelTool.LogHelper.WriteLog(ex.ToString());
                        }
                    });
                }
            }
            catch (System.Exception ex)
            {
                InitCount();
                Growl.Error(ex.Message);
                BtLabelTool.LogHelper.WriteLog(ex.ToString());
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                rfidBLL.LighteRfid();
            }
            catch (Exception ex)
            {
                HandyControl.Controls.MessageBox.Error(ex.Message);
            }
        }
        private void ToggleButton_Checked(object sender, RoutedEventArgs e)
        {
            try
            {
                if (rfidBLL.OpenRfid()==false)
                {
                    HandyControl.Controls.Growl.Warning("RFID读写器打开失败！");
                }
                timer1.Start();
            }
            catch (System.Exception ex)
            {
                Growl.Error(ex.Message);
                BtLabelTool.LogHelper.WriteLog(ex.ToString());
            }
        }

        private void ToggleButton_Unchecked(object sender, RoutedEventArgs e)
        {
            try
            {
                timer1.Stop();
                rfidBLL.CloseRfid();
            }
            catch (System.Exception)
            {
            }
        }
        private void InitCount()
        {
            int ing = 0;
            int pass = 0;
            int fail = 0;
            foreach (var item in viewModel.MacItems)
            {
                if (item.BackColor==Brushes.Gold)
                {
                    ing++;
                }
                if (item.BackColor == Brushes.YellowGreen)
                {
                    pass++;
                }
                if (item.BackColor == Brushes.Tomato)
                {
                    fail++;
                }
            }
            viewModel.AllCount = ing + pass + fail;
            viewModel.IngCount = ing;
            viewModel.PassCount = pass;
            viewModel.FailCount = fail;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            viewModel.MacItems.Clear();
            viewModel.AllCount = 0;
            viewModel.IngCount = 0;
            viewModel.PassCount = 0;
            viewModel.FailCount = 0;
        }
    }
}
